'use strict';
var clientWidgets = angular.module('clientWidgets');
var clientApp = angular.module('clientApp');

clientApp.directive('waterfallWidget', ['$rootScope', 'Constant', 'Util', 'iScrollUtil', 'DomUtil', 'WidgetUtil',
    function($rootScope, Constant, Util, iScrollUtil, DomUtil, WidgetUtil) {
        console.log('directive init');
        return {
            templateUrl: '/ext/themes/flat/widget/list/waterfall/view/main.html',
            replace: true,
            //transclude: true,
            restrict: 'E',
            scope: {
                vo: '=vo',
                propMap: '=propModel',
                contrlAct: '&',
                itemSelect: '&'
            },
            link: function(scope, element, attrs) {

                var genWaterfall = function () {
                    var data = genData(contentWidth);
                    generateWaterfall(scope.msnry, data);
                };
                var genData = function (contentWidth) {
                    var date = [];
                    for (var i = 0; i < scope.items.length; i++) {
                        date.push({
                            id: scope.items[i].id,
                            image: Constant.UploadUrl + scope.items[i].image,
                            title: scope.items[i].title,
                            width: contentWidth,
                            url: '#'
                        });
                    }
                    return date;
                };

                var generateWaterfall = function (msnry, data ) {
                    if ( !data || !data.length ) {
                        return;
                    }

                    var items = [];
                    var fragment = document.createDocumentFragment();
                    for ( var i=0, len = data.length; i < len; i++ ) {
                        var item = makeWaterfallItem( data[i] );
                        items.push( item );
                        fragment.appendChild( item );
                    }

                    var imgLoad = imagesLoaded( fragment );
                    imgLoad.on( 'progress', function( instance, image ) {
                        var item = image.img.parentNode.parentNode;
                        container.appendChild( item );
                        msnry.appended( item );
                    });
                    imgLoad.on( 'done', function( instance ) {
                        $(element).find('.wrapper').height(Util.getScreenSize().h - 50 + 'px');
                        setTimeout(function() {
                            initIscroll();
                        }, 20);
                    });
                };

                var makeWaterfallItem = function ( dataObj ) {
                    var item = document.createElement('div');
                    item.id = dataObj.id;
                    item.className = 'item';
                    item.style.width = dataObj.width + 'px';

                    var span = document.createElement('span');
                    var img = document.createElement('img');
                    img.src = dataObj.image;
                    img.style.width = dataObj.width + 'px';
                    var title = document.createElement('p');
                    title.className = 'title';
                    title.textContent = dataObj.title;
                    span.appendChild( img );
                    span.appendChild( title );
                    item.appendChild( span );

                    return item;
                };

                var initIscroll = function() {
                    if (!scope.myScroll) {
                        scope.myScroll = new IScroll($('.wrapper')[0], {
                            scrollX: false,
                            scrollY: true,
                            mouseWheel: true,
                            click: true
                        });
                        scope.myScroll.on('scrollMove', function() {
                            var $pullDown = $('.pulldown');
                            var $pullUp = $('.pullup');

                            if (this.y > 60) {
                                $pullDown.addClass('flip').find('.label').html('Release to refresh...');
                                scope.action = 'reset';
                            } else {
                                $pullDown.removeClass('flip').find('.label').html('Pull down to refresh...');
                            }
                            if (this.maxScrollY - this.y > 60) {
                                $pullUp.addClass('flip').find('.label').html('Release to load more...');
                                scope.action = 'next_page';
                            } else {
                                $pullUp.removeClass('flip').find('.label').html('Pull up to load more...');
                            }
                        });
                        scope.myScroll.on('scrollEnd', function() {
                            console.log('scrollEnd');
                            var $wrapper = $('.wrapper');
                            var $pullDown = $('.pulldown');
                            var $pullUp = $('.pullup');

                            if ($pullDown.hasClass('flip')) {
                                $wrapper.addClass('pulldownrefresh');
                                this.refresh();
                                $pullDown.removeClass('flip').addClass('loading').find('.label').html('Loading...');
                                pullDownAction($wrapper);
                            }
                            if ($pullUp.hasClass('flip')) {
                                $pullUp.removeClass('flip').addClass('loading').find('.label').html('Loading...');
                                pullUpAction($wrapper);
                            }

                           if(scope.action) { // a valid scroll from
                               scope.$emit(scope.vo.code + '_' + scope.action);
                           }
                        });
                    }
                };

                var pullDownAction = function ($wrapper) {
                    var $pullDown = $wrapper.find('.pulldown');
                    setTimeout(function() {
                        $wrapper.removeClass('pulldownrefresh');
                        $pullDown.removeClass('flip loading').find('.label').html('Pull down to refresh...');
                        scope.myScroll.refresh();
                    }, 3000);
                };

                var pullUpAction = function ($wrapper) {
                    var $pullUp = $wrapper.find('.pullup');
                    setTimeout(function() {
                        $pullUp.removeClass('flip loading').find('.label').html('Pull up to load more...');
                        scope.myScroll.refresh();
                    }, 3000);
                };

                var display = function () {
                    DomUtil.loadComponent('/ext/themes/flat/widget/list/waterfall/lib/imagesloaded.pkgd.js', function(){
                        DomUtil.loadComponent('/ext/themes/flat/widget/list/waterfall/lib/masonry.pkgd.js', function(){
                            if (scope.action == 'reset') {
                                scope.allData = [];
                                $(element).find('.waterFall .item').remove();
                                if (!!scope.msnry) {
                                    scope.msnry.destroy();
                                }
                            }
                            scope.msnry = new Masonry( container, {
                                columnWidth: contentWidth,
                                itemSelector: '.item',
                                gutter: gutter
                            });

                            var newVo = WidgetUtil.convert(scope.vo, scope.propMap);
                            scope.items = newVo.data;
                            scope.allData = scope.allData.concat(scope.items);

                            genWaterfall();
                        });
                    })
                };

                console.log('link function entered');
                scope.action = 'reset';
                scope.allData = [];
                var gutter = 10;
                var contentWidth = DomUtil.getColumnWidth($(element).width(), 10);
                var container = $(element).find('.waterFall')[0];
                $(container).delegate('.item', 'click', function() {
                    var item = Util.findInArray(scope.allData, $(this).attr('id'));
                    scope.$emit(scope.vo.code + '_select', item);
                });
                $(element).css('margin-left', gutter / 2 + 'px');
                scope.$watch('vo', function (newVal, oldVal) {
                    if (newVal) {
                        if (newVal.status == Constant.HTTP_RETURN_CODE_NO_MORE) {
                            scope.noMore = true;
                            iScrollUtil.noMore(scope, element);
                        } else {
                            display();
                        }
                    }
                });
            }
        };
    }]);


